﻿using Abp.Application.Services;
using Abp.Application.Services.Dto;
using Abp.Domain.Repositories;
using Abp.Extensions;
using Abp.Linq.Extensions;
using Microsoft.EntityFrameworkCore;
using Sunlit.Business.IO;
using Sunlit.Business.Policies.Dto;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading.Tasks;

namespace Sunlit.Business.Policies
{
    public class PolicyCateAppService: AsyncCrudAppService<PolicyCate, PolicyCateDto,int,GetAllPolicyCateInput
        ,CreatePolicyCateInput,UpdatePolicyCateInput>, IPolicyCateAppService
    {
        private readonly IAppFolders _appFolders;
        public PolicyCateAppService(IRepository<PolicyCate> repository,
            IAppFolders appFolders) : base(repository)
        {
            _appFolders = appFolders;
        }
        protected override IQueryable<PolicyCate> CreateFilteredQuery(GetAllPolicyCateInput input)
        {
            return base.CreateFilteredQuery(input)
                .WhereIf(!input.Name.IsNullOrEmpty(), p => p.Name.Contains(input.Name));
        }
        /// <summary>
        /// 获取所有类别
        /// </summary>
        /// <returns></returns>
        public async Task<List<PolicyCateDto>> GetAllList()
        {
            var list = await Repository.GetAllListAsync();
            return ObjectMapper.Map<List<PolicyCateDto>>(list);
        }
        /// <summary>
        /// 获取首页显示的所有类别
        /// </summary>
        /// <returns></returns>
        public async Task<List<PolicyCateDto>> GetAllOnHomeList()
        {
            var list = await Repository.GetAll()
                .Where(c => c.ShowOnHome)
                .ToListAsync();
            return ObjectMapper.Map<List<PolicyCateDto>>(list);
        }
        public override async Task DeleteAsync(EntityDto<int> input)
        {
            var deleteEntity = await this.GetAsync(input);
            if (!string.IsNullOrWhiteSpace(deleteEntity.ImageUrl))
            {
                var fileNameWithoutExt = Path.GetFileNameWithoutExtension(deleteEntity.ImageUrl);
                var pictureType = fileNameWithoutExt.Split("_").First();
                var userHonorPath = Path.Combine(_appFolders.PictureUpladFolder, pictureType);
                AppFileHelper.DeleteFilesInFolderIfExists(userHonorPath, fileNameWithoutExt);
            }
            await base.DeleteAsync(input);
        }
    }
}
